import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import React from "react";
import { Button, Checkbox, Input } from "antd";
import CpasTable from "../../../index";
import AntTabs from "~/public/cpas-ui/components-ui/ant-components/AntTab";
import { consts } from "../../../../../tools/consts";
import ForwardedWorkerPaperTabPanel from "./WorkerPaperTabPanel";
import ForwardedBaseReportTabPanel from "./BaseReportTabPanel";
import CustomFormulaService from "../../../classes/CustomFormulaService";
import { dynamicFormulaReplace } from "../../../classes/DynamicFormula";
import { getCorpData, getReportMenu, } from "../../../classes/HandSonGridToolService/getDataSourceService";
import { AntToolTip } from "~/public/cpas-ui";
export default class CellDataV2 extends React.Component {
    // 当前窗口中的CpasTable组件
    currentCpasTableRef = React.createRef();
    // 底稿panel Ref
    currentWorkerPaperPanel = React.createRef();
    // 报告基础数据panel Ref
    currentBaseReportPanel = React.createRef();
    // faq:Modal 在关闭时会将内容进行 memo 从而避免关闭过程中的内容跳跃
    // 通过此状态来区分是否要执行表格数据同步
    isNeedSyncTableData = true;
    constructor(props) {
        super(props);
        this.currentCpasTableCellClick = this.currentCpasTableCellClick.bind(this);
        this.currentSourceTabsChange = this.currentSourceTabsChange.bind(this);
        this.currentCpasTableCellClick = this.currentCpasTableCellClick.bind(this);
        this.generateCustomFormula = this.generateCustomFormula.bind(this);
        this.clearFormula = this.clearFormula.bind(this);
        this.dynamicModelCheckBoxChange =
            this.dynamicModelCheckBoxChange.bind(this);
        this.state = {
            formulaVal: "=FS_CELL",
            currentTabActiveKey: consts.ReportTabKey,
            rawCpasTableCoords: { row: null, col: null },
            dynamic: {
                isDynamic: false,
                dynmiacType: null,
                dynamicModel: true,
            },
            sourceData: {
                baseReportCategoryData: [],
                workePaperRawData: [],
            },
        };
    }
    // 获取底稿取数源panel
    get getWorkerPaperPanel() {
        return this.currentWorkerPaperPanel.current;
    }
    // 获取报告基础数据源panel
    get getBaseReportPanel() {
        return this.currentBaseReportPanel.current;
    }
    // 获取取数cpasTable
    get getCurrentCpasTable() {
        return this.currentCpasTableRef.current;
    }
    // 获取父级引用
    get getMenuToolRef() {
        return this.props.menuToolRef;
    }
    // 获取底表引用
    get rawCpasTable() {
        return this.props.menuToolRef?.gridRef;
    }
    //获取底表坐标
    // raw 底表坐标
    // current 单元格取数坐标
    getCpasTableCellCoords(type) {
        if (type === "raw") {
            return this.rawCpasTable.hot.getSelectedLast() || null;
        }
        else {
            return this.getCurrentCpasTable.hot.getSelectedLast() || null;
        }
    }
    //获取取数表当前数据
    getCurrentCpasTableIGridData() {
        return this.getCurrentCpasTable.getCpasTableGrid();
    }
    buildFormula(params) {
        const { tname, rmap, cmap, year } = params;
        return `FS_CELL("${tname}","${rmap}","${cmap}","${year}")`;
    }
    componentDidUpdate(prevProps, prevState) {
        if (this.isNeedSyncTableData === true ||
            prevState.sourceData !== this.state.sourceData) {
            this.initShowLogic();
            // 只要同步过一次, 在本窗口内就不需再触发了.该开关由父容器操作该属性
            // 原因参考 isNeedSyncTableData 注释
            this.isNeedSyncTableData = false;
        }
    }
    componentDidMount() {
        // 初始化报告基础数据数据源, 用于做页签初始定位
        this.initSourceData();
    }
    async initSourceData() {
        const baseReportCategoryData = await this.getBaseReportCategoryData();
        const workerPaperRawData = await this.getWorkerPaperRawData();
        const data = {
            baseReportCategoryData: baseReportCategoryData,
            workePaperRawData: workerPaperRawData,
        };
        this.setState({
            sourceData: {
                ...data,
            },
        });
    }
    async getBaseReportCategoryData() {
        let data = await getCorpData();
        const transferData = data.map((item) => {
            return { label: item.dataSrcName, value: item.dmName };
        });
        return transferData;
    }
    async getWorkerPaperRawData() {
        return await getReportMenu();
    }
    /**
     * 初始化显示逻辑
     */
    initShowLogic() {
        // 同步源数据
        this.syncRawTable();
        // 获取当前底表的坐标
        const selected = this.getCpasTableCellCoords("raw");
        if (!selected) {
            return;
        }
        const [startRow, startCol, endRow, endCol] = selected;
        const rawCoords = this.state.rawCpasTableCoords;
        // 防止触发重新渲染, 每次父窗口触发该弹出层显示的时候. 会触发componentDidUpdate,进行底表选中的单元格重新显示状态.
        // if (rawCoords.row === startRow && rawCoords.col === startCol) {
        //   return;
        // }
        // 存储当前底表坐标, 用于判断是否刷新组件逻辑
        this.setState({
            rawCpasTableCoords: { row: startRow, col: startCol },
        });
        const formula = this.rawCpasTable.hot.getSourceDataAtCell(startRow, startCol);
        // 定位单元格
        this.positionCell(selected, formula);
    }
    /**
     * 判断单元格是否为动态公式模式,只有母列上才开启动态公式
     */
    setlIsDynamicByCell(row, col) {
        // 获取当前单元格属性
        const cellsMeta = this.getCurrentCpasTable.hot.getCellMeta(row, col);
        const columnKey = cellsMeta["columnKey"];
        // 是期间类型，并且是母列
        if (cellsMeta.timeColumn &&
            columnKey.startsWith(cellsMeta["timeColumn"].mainKey)) {
            // 标记期间类型母列
            this.setState({
                dynamic: {
                    isDynamic: true,
                    dynmiacType: cellsMeta.timeColumn.type,
                    dynamicModel: this.state.dynamic.dynamicModel,
                },
                currentTabActiveKey: consts.ReportTabKey,
            });
        }
        else {
            this.setState({
                dynamic: {
                    isDynamic: false,
                    dynmiacType: null,
                    dynamicModel: this.state.dynamic.dynamicModel,
                },
            });
        }
    }
    /**
     * positionCell
     * 接收坐标，定位当取数表的单元格选中位置，以及公式值
     */
    positionCell(selected, formula) {
        if (!selected) {
            return;
        }
        const [startRow, startCol, endRow, endCol] = selected;
        if (startRow < 1 || startCol < 1) {
            return;
        }
        // 设置当前表定位
        this.getCurrentCpasTable.hot.selectCell(startRow, startCol);
        // 如果是期间类型,则开启动态公式模式
        this.setlIsDynamicByCell(startRow, startCol);
        let isFormula = CustomFormulaService.isCustomFormula(formula);
        if (isFormula) {
            this.setState({
                formulaVal: formula,
            });
        }
        else {
            this.setState({
                formulaVal: "=FS_CELL",
            });
        }
        // 触发公式条件回显 ,  公式变化才触发
        // if (formula !== this.state.formulaVal) {
        this.showFormulaDataSourceState(formula, isFormula);
        // }
    }
    /**
     * 同步rawCpasTable到当前表格
     */
    syncRawTable() {
        const rawTableData = this.rawCpasTable.getCpasTableGrid();
        this.getCurrentCpasTable.reloadTable(rawTableData);
    }
    checkIsDynamicFormula(formula) {
        return formula.includes("{");
    }
    /**
     * 根据单元格公式进行状态回显
     * @param formula
     */
    showFormulaDataSourceState(formula, isFormula) {
        let tname, year, cmap, rmap, source = null;
        let tabKey = this.state.currentTabActiveKey;
        if (isFormula) {
            let formulaParams = CustomFormulaService.getHyperCustomFormulaParams(formula);
            const formulaSourceName = JSON.parse(formulaParams[0]);
            // 检测公式是否为动态公式
            let isDynamicFormula = this.checkIsDynamicFormula(formula);
            // 根据表名判断数据来源
            tabKey = this.getTabKeyByFormulaSource(formulaSourceName);
            if (tabKey === consts.ReportTabKey) {
                tname = formulaSourceName;
            }
            else {
                tname = this.getWorkerPaperNameByFormulaSource(formulaSourceName);
                source = formulaSourceName;
            }
            // 激活页签
            this.setState({
                currentTabActiveKey: tabKey,
            });
            // 构建条件
            rmap = JSON.parse(formulaParams[1]).replace(/{|}/g, ""); //去动态括号
            cmap = JSON.parse(formulaParams[2]).replace(/{|}/g, "");
            year = JSON.parse(formulaParams[3]).replace(/{|}/g, "");
        }
        // 企业基础数据
        if (tabKey === consts.ReportTabKey) {
            this.getBaseReportPanel.updateSearchCondition({
                tname,
                rmap,
                cmap,
                year,
            });
        }
        //底稿结构化
        else {
            this.getWorkerPaperPanel.updateSearchCondition({
                tname,
                rmap,
                cmap,
                year,
                source,
            });
        }
    }
    /**
     * 底稿类型根据取数源获取底稿名称
     */
    getWorkerPaperNameByFormulaSource(formulaSourceName) {
        const workePaperRawData = this.state.sourceData.workePaperRawData;
        let formulaSourcePrefix = formulaSourceName.substring(0, 3);
        let filteredData = workePaperRawData.filter((item) => item.ReportItemCode === formulaSourcePrefix);
        if (filteredData.length > 0) {
            return filteredData[0].ReportItem;
        }
        else {
            return "";
        }
    }
    /**
     * 根据表名判断页签
     * @param formulaSourceName
     */
    getTabKeyByFormulaSource(formulaSourceName) {
        // 获取报告基础数据的表名源
        let dataSourceArray = this.state.sourceData.baseReportCategoryData;
        if (dataSourceArray.length === 0)
            return consts.ReportTabKey;
        // 进行匹配返回对应的tabkey
        return dataSourceArray.some((item) => item.value === formulaSourceName)
            ? consts.ReportTabKey
            : consts.WpTabKey;
    }
    /**
     * 构建公式, 父子通讯, 子调用
     * @param e , dev表格双击事件的返回值
     * @param param
     */
    generateCustomFormula(e, tname, year, category) {
        let rmap, cmap = "";
        let columnType = e.column.dataType;
        let vaildate = true;
        if (columnType !== "number") {
            vaildate = false;
            this.getMenuToolRef.showErrorNotify("该列非数字列,请选择数字列");
        }
        if (!tname) {
            vaildate = false;
            this.getMenuToolRef.showErrorNotify("未找到对应的数据源表名");
        }
        if (!year) {
            vaildate = false;
            this.getMenuToolRef.showErrorNotify("未找到对应的年度");
        }
        //   确定rmap
        rmap = e.key || "";
        if (!rmap) {
            vaildate = false;
            this.getMenuToolRef.showErrorNotify("未找到主键");
        }
        //   确定cmap
        cmap = e.column.caption || "";
        if (!cmap) {
            vaildate = false;
            this.getMenuToolRef.showErrorNotify("未找到数据列");
        }
        const selected = this.getCpasTableCellCoords("current");
        if (!selected) {
            vaildate = false;
            this.getMenuToolRef.showErrorNotify("请选择取数表中的单元格");
        }
        if (!vaildate) {
            return;
        }
        let formula = "";
        if (this.state.dynamic.isDynamic && this.state.dynamic.dynamicModel) {
            if (category === "资产" || category === "负债") {
                category = "资产负债表";
            }
            if (category === "利润") {
                category = "利润表";
            }
            //期间类型动态公式
            formula = dynamicFormulaReplace({
                dynamicCondition: true,
                dynamicType: "year",
                paramType: "default",
                type: "rs",
                formulaData: {
                    tname: tname,
                    rowVal: rmap,
                    colVal: cmap,
                },
                rowData: {
                    report: category,
                    caption: cmap,
                },
            });
            const selected = this.getCpasTableCellCoords("current");
            if (selected) {
                const [startRow, startCol] = selected;
                const cellsMeta = this.getCurrentCpasTable.hot.getCellMeta(startRow, startCol);
                const mainKey = cellsMeta["timeColumn"].mainKey;
                const currentCpasTableData = this.getCurrentCpasTable.getCpasTableGrid().data;
                const { rmap, cmap } = this.getCurrentCpasTable.gridService.getMapsByCoords(currentCpasTableData, { row: startRow, col: startCol });
                if (!rmap) {
                    this.getMenuToolRef.showErrorNotify("未检测到当前行的主键,请先设置行的主键");
                    return;
                }
                this.saveDynamicFormulaToMainTimeColumn(formula, mainKey, rmap, startCol);
            }
        }
        else {
            //普通公式
            formula = this.buildFormula({
                tname,
                rmap,
                cmap,
                year,
            });
        }
        if (!formula) {
            this.getMenuToolRef.showErrorNotify("公式解析失败");
            return;
        }
        formula = "=" + formula;
        // 设置公式
        this.setState({
            formulaVal: formula,
        });
        const [startRow, startCol] = selected;
        // 设置单元格数据
        this.getCurrentCpasTable.hot.setSourceDataAtCell(startRow, startCol, formula);
        const sourceData = this.getCurrentCpasTable.hot.getSourceData();
        console.log(sourceData);
    }
    /**
     * 获取当前母列的leafOrder
     */
    getLeafOrderByTimeColumn(colIndex) {
        const currentCpasTable = this.getCurrentCpasTable;
        const headerServiceInstance = currentCpasTable.headerService;
        const headerColumn = headerServiceInstance.headerColumn;
        const currentKey = headerColumn[colIndex].key;
        const mainGroupMark = currentKey.split("||||")[1];
        // mainGroupMark 为期间类型下子节点的坐标
        // level 层级 , index 在该层级下的顺序 , count 在整个节点中的顺序（深度遍历） , leafOrder : 叶子节点的顺序
        // 结构为`${key}||||${level}-${index}-${count}-${leafOrder}`
        const mainGroupLeafOrder = !mainGroupMark
            ? "self" //self 指的是无子节点, 即无主节点的子列
            : mainGroupMark.split("-")[3];
        return mainGroupLeafOrder;
    }
    /**
     * 设置期间类型动态公式存储条件
     * dynamicFormula :动态公式
     * mainKey : 期间类型目列主键
     * cmap : 设置列的key , 母列可能是复合表头，存在不同headerKey为母的情况。后台解析需要根据该值来进行分组赋值
     * rmap :
     */
    saveDynamicFormulaToMainTimeColumn(dynamicFormula, mainKey, rmap, colIndex) {
        const currentCpasTable = this.getCurrentCpasTable;
        const headerServiceInstance = currentCpasTable.headerService;
        const headerJson = headerServiceInstance.headJson;
        const mainGroupLeafOrder = this.getLeafOrderByTimeColumn(colIndex);
        const mainKeyNode = headerServiceInstance.findNodeByKey(mainKey, headerJson);
        const lastConfig = mainKeyNode?.config || {};
        if (!lastConfig.timeColumn) {
            this.getMenuToolRef.showErrorNotify("该列不支持动态公式");
            return;
        }
        // Key 存储的是行的rmap , 和坐在母列的顺序
        const dynamicFormulaKey = rmap + "|||" + mainGroupLeafOrder;
        const lastConfigDynamicFormula = lastConfig.timeColumn?.dynamicFormula;
        if (lastConfigDynamicFormula) {
            lastConfigDynamicFormula[dynamicFormulaKey] = dynamicFormula;
        }
        else {
            lastConfig["timeColumn"]["dynamicFormula"] = {};
            lastConfig["timeColumn"]["dynamicFormula"][dynamicFormulaKey] =
                dynamicFormula;
        }
        const update_config_headerJson = headerServiceInstance.updateNodeByKey(mainKey, headerJson, lastConfig, true);
        headerServiceInstance.headerCompute(update_config_headerJson);
    }
    // 事件-----------------------------------------------------------
    // 清空公式
    clearFormula() {
        const selected = this.getCpasTableCellCoords("current");
        if (selected) {
            const [startRow, startCol, endRow, endCol] = selected;
            this.setState({
                formulaVal: "=FS_CELL",
            });
            // 清空CpasTable单元格公式为Null
            this.getCurrentCpasTable.hot.setSourceDataAtCell(startRow, startCol, null);
            // baseReport dev表格取消选择
            this.getBaseReportPanel.clearFormula();
            // 如果是动态公式清空 timeColumn中的 dynamicFormulas{}对应项目
            const cellsMeta = this.getCurrentCpasTable.hot.getCellMeta(startRow, startCol);
            const columnKey = cellsMeta["columnKey"];
            const mainKey = cellsMeta["timeColumn"].mainKey;
            // 是期间类型，并且是母列
            if (cellsMeta.timeColumn && columnKey.startsWith(mainKey)) {
                // 获取主键配置
                const mainConfig = this.getCurrentCpasTable.headerService.findNodeByKey(mainKey).config;
                // 获取主键当前的动态公式
                const dynamicFormula = mainConfig.timeColumn.dynamicFormula;
                // 获取当前表格数据
                const currentData = this.getCurrentCpasTable.getCpasTableGrid().data;
                // 获取当前单元格的rmap,cmap
                const { rmap, cmap } = this.getCurrentCpasTable.gridService.getMapsByCoords(currentData, {
                    row: startRow,
                    col: startCol,
                });
                if (dynamicFormula) {
                    const mainGroupLeafOrder = this.getLeafOrderByTimeColumn(startCol);
                    delete dynamicFormula[`${rmap}|||${mainGroupLeafOrder}`];
                    // 清空垃圾数据, 检测当前表的动态公式列表是否存在垃圾数据,例如修改了rmap
                    const allRmap = this.getCurrentCpasTable.gridService.getAllRowsMaps(currentData);
                    let keysToDelete = [];
                    // 检测出待删除的key
                    for (let key in dynamicFormula) {
                        const key_rmap = key.split("|||")[0];
                        if (!allRmap.includes(key_rmap)) {
                            keysToDelete.push(key);
                        }
                    }
                    // 执行删除
                    for (let i = 0; i < keysToDelete.length; i++) {
                        let key = keysToDelete[i];
                        delete dynamicFormula[key];
                    }
                    const headerJson = this.getCurrentCpasTable.headerService.headJson;
                    const after_update_header = this.getCurrentCpasTable.headerService.updateNodeByKey(mainKey, headerJson, {
                        ...mainConfig,
                    }, true);
                    this.getCurrentCpasTable.headerService.headerCompute(after_update_header);
                }
            }
        }
    }
    // 取数表选择单元格进行状态回显
    async currentCpasTableCellClick(e, param) {
        const { row, col } = param;
        if (row < 0) {
            return;
        }
        const formula = this.getCurrentCpasTable.hot.getSourceDataAtCell(row, col);
        const selected = this.getCpasTableCellCoords("current");
        this.positionCell(selected, formula);
        // 如果是期间类型,则开启动态公式模式
        this.setlIsDynamicByCell(row, col);
    }
    // 判断当前选择单元格是否为母列
    checkIsMainColumn() {
        const selected = this.getCpasTableCellCoords("current");
        if (selected) {
            const [startRow, startCol] = selected;
            const cellsMeta = this.getCurrentCpasTable.hot.getCellMeta(startRow, startCol);
            const columnKey = cellsMeta["columnKey"];
            const mainKey = cellsMeta["timeColumn"]?.mainKey;
            if (!mainKey) {
                return false;
            }
            if (cellsMeta.timeColumn && columnKey.startsWith(mainKey)) {
                return true;
            }
        }
        return false;
    }
    // 页签切换
    async currentSourceTabsChange(activeKey) {
        this.setState({
            currentTabActiveKey: activeKey,
        });
    }
    // isDynamicModel
    dynamicModelCheckBoxChange(e) {
        const value = e.target.checked;
        // 如果当前是母列, 则切换到报告基础数据页签
        const isMainColumn = this.checkIsMainColumn();
        if (isMainColumn) {
            this.setState({
                currentTabActiveKey: consts.ReportTabKey,
            });
        }
        this.setState({
            dynamic: {
                isDynamic: this.state.dynamic.isDynamic,
                dynmiacType: this.state.dynamic.dynmiacType,
                dynamicModel: value,
            },
        });
    }
    render() {
        return (_jsxs(_Fragment, { children: [_jsxs("div", { className: "con mb-10", children: [_jsxs("div", { className: "flex-start mb-10", children: [_jsx("div", { className: "f12", children: "\u53D6\u6570\u516C\u5F0F\uFF1A" }), _jsx("div", { style: {
                                        width: "calc(100% - 300px)",
                                        display: "flex",
                                        alignItems: "center",
                                        justifyContent: "space-between",
                                    }, children: _jsx(Input, { placeholder: "=FS_CELL(\u201C\u62A5\u544A\u57FA\u7840\u6570\u636E \u53D6\u6570\u6E90\u4E0B\u62C9\u201D,\u201Ddev\u8868\u884C\u201D,\u201Ddev\u8868\u5217\u201D,\u201D2017\u5E74\u5EA6\u201D)", value: this.state.formulaVal }) }), _jsx(Button, { style: { marginLeft: 20 }, onClick: this.clearFormula, children: "\u6E05\u7A7A\u516C\u5F0F" }), _jsx(AntToolTip, { title: "勾选该选项表示母列支持设置动态公式", children: _jsx(Checkbox, { style: { marginLeft: 20 }, checked: this.state.dynamic.dynamicModel, onChange: this.dynamicModelCheckBoxChange, children: "\u6279\u91CF\u6A21\u5F0F" }) })] }), _jsx("div", { style: { height: "250px", border: "0px solid #000" }, children: _jsx(CpasTable, { ref: this.currentCpasTableRef, name: "innerTable", type: "ds", formulaTimeSlice: true, model: "read", isTest: false, gridData: null, isShowMenuToolBar: false, mapColumnsList: [], mapRowsList: [], afterOnCellMouseDown: this.currentCpasTableCellClick, numberZeroReplace: " " }) })] }), _jsx("div", { className: "con", children: _jsxs(AntTabs, { tabBarStyle: { background: "#FFF" }, onChange: this.currentSourceTabsChange, activeKey: this.state.currentTabActiveKey, children: [_jsx(AntTabs.Panel, { tab: consts.ReportTabKey, style: { marginTop: "5px" }, children: _jsx(ForwardedBaseReportTabPanel, { baseReportCategoryData: this.state.sourceData.baseReportCategoryData, activeKey: this.state.currentTabActiveKey, dynamic: this.state.dynamic, ref: this.currentBaseReportPanel, generateCustomFormula: this.generateCustomFormula }) }, consts.ReportTabKey), _jsx(AntTabs.Panel, { tab: consts.WpTabKey, disabled: this.state.dynamic.isDynamic && this.state.dynamic.dynamicModel, forceRender: true, style: { marginTop: "5px" }, children: _jsx(ForwardedWorkerPaperTabPanel, { itemName: this.props.itemName, activeKey: this.state.currentTabActiveKey, workePaperRawData: this.state.sourceData.workePaperRawData, generateCustomFormula: this.generateCustomFormula, ref: this.currentWorkerPaperPanel }) }, consts.WpTabKey)] }) })] }));
    }
}
